package com.taotao.web.service;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.service.HttpClientService;
import com.taotao.web.bean.Item;
import com.taotao.web.bean.ItemDesc;

@Service
public class ItemService {
	
	@Autowired
	private HttpClientService httpClientService;
	
	@Autowired
	private PropertisService propertisService;
	
	@Autowired
	private RedisService redisService;

	/**
	 * 调用后台接口，根据商品id，获取商品对象
	 * @param id
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public Item getItemById(Long id) throws ClientProtocolException, IOException {
		String key = "TT_WEB_ITEM_"+id;
		// 从缓存中取
		try {
			String jsonValue = redisService.get(key);
			if (StringUtils.isNoneBlank(jsonValue)){
				Item item = PropertisService.MAPPER.readValue(jsonValue, Item.class);
				return item;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String url = "http://manage.taotao.com/rest/api/item/"+id;
		String jsonString = httpClientService.doGet(url );
		// 将json转化成对象
		Item item = PropertisService.MAPPER.readValue(jsonString, Item.class);
		
		// 将结果缓存到redis中
		try {
			String value = PropertisService.MAPPER.writeValueAsString(item);
			redisService.set(key, value, 60*30);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return item;
	}
	
	/**
	 * 调用后台接口，根据商品id，获取商品描述对象
	 * @param id
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public ItemDesc getItemDescById(Long id) throws ClientProtocolException, IOException {
		String key = "TT_WEB_ITEM_DESC_"+id;
		// 从缓存中取
		try {
			String jsonValue = redisService.get(key);
			if (StringUtils.isNoneBlank(jsonValue)){
				ItemDesc itemDesc = PropertisService.MAPPER.readValue(jsonValue, ItemDesc.class);
				return itemDesc;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String url = "http://manage.taotao.com/rest/api/item/desc/"+id;
		String jsonString = httpClientService.doGet(url );
		// 将json转化成对象
		ItemDesc itemDesc = PropertisService.MAPPER.readValue(jsonString, ItemDesc.class);
		
		// 将结果缓存到redis中
		try {
			String value = PropertisService.MAPPER.writeValueAsString(itemDesc);
			redisService.set(key, value, 60*30);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return itemDesc;
	}

}
